package demo;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExcelReaderUtil {

    public static List<Map<String, String>> readExcelAsMapByHeader(File file) {
        List<Map<String, String>> resultList = new ArrayList<>();


        EasyExcel.read(file, new AnalysisEventListener<Map<Integer, String>>() {
            private List<String> headerList;
            final SimpleDateFormat inputFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            final SimpleDateFormat inputFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//            private String formatDateTime(String dateTimeStr) {
//                try {
//                    // Try to parse with first format (yyyy/MM/dd HH:mm:ss)
//                    Date date = null;
//                    try {
//                        date = inputFormat1.parse(dateTimeStr);
//                    } catch (ParseException e1) {
//                        // If first format fails, try second format (yyyy-MM-dd HH:mm:ss)
//                        try {
//                            date = inputFormat2.parse(dateTimeStr);
//                        } catch (ParseException e2) {
//                            // If both formats fail, return original string
//                            return dateTimeStr;
//                        }
//                    }
//                    return outputFormat.format(date);
//                } catch (Exception e) {
//                    // If any unexpected error occurs, return original string
//                    return dateTimeStr;
//                }
//            }

            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                if (headerList == null) {
                    throw new RuntimeException("尚未读取表头，数据行读取失败");
                }
//                Map<String, String> rowMap = new LinkedHashMap<>();
//                for (int i = 0; i < headerList.size(); i++) {
//                    rowMap.put(headerList.get(i), data.getOrDefault(i, ""));
//                }
//                resultList.add(rowMap);
                Map<String, String> rowMap = new LinkedHashMap<>();
                for (int i = 0; i < headerList.size(); i++) {
                    String header = headerList.get(i);
                    String value = data.getOrDefault(i, "");

                    // Format the date if the header is "操作时间"
                    if ("操作时间".equals(header) && !value.isEmpty()) {
                        value = DateUtil.format(DateUtil.parse(value), "yyyy-MM-dd HH:mm:ss");
                    } else if ("总库存调整数量".equals(header) && !value.isEmpty()) {
                        value = formatInventoryAdjustment(value);
                    }

                    rowMap.put(header, value);
                }
                resultList.add(rowMap);
            }

            private String formatInventoryAdjustment(String numberStr) {
                try {
                    // Parse the number string to BigDecimal
                    BigDecimal number = new BigDecimal(numberStr.trim());
                    // Set scale to 0 with rounding mode (HALF_UP is common for business calculations)
                    number = number.setScale(0, RoundingMode.HALF_UP);
                    // Return the string representation without decimal places
                    return number.toString();
                } catch (NumberFormatException e) {
                    // If parsing fails, return original string
                    return numberStr;
                }
            }

            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                headerList = new ArrayList<>();
                for (int i = 0; i < headMap.size(); i++) {
                    String header = headMap.get(i);
                    if (header == null || header.trim().isEmpty()) {
                        header = "列" + (i + 1);
                    }
                    headerList.add(header.trim());
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // no-op
            }
        }).sheet().headRowNumber(1).doRead();

        return resultList;
    }
}